package cn.xiaolang.function.urlparams;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dean
 * @date 2023/7/13
 */
public class HandlerUrlParams {

    /**
     * http://localhost:8080/dk/doGet/oauth2/code/dean
     */
    @Test
    public void replacePlaceHolder() {
        String reqUrlTemplate = "{baseUrl}/{action}/oauth2/code/{registrationId}";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("registrationId", "dean");
        uriVariables.put("baseUrl", "http://localhost:8080/dk");
        uriVariables.put("action", "doGet");
        String reqUrl = UriComponentsBuilder.fromUriString(reqUrlTemplate)
                .buildAndExpand(uriVariables)
                .toUriString();
        Assert.assertEquals("http://localhost:8080/dk/doGet/oauth2/code/dean", reqUrl);
    }

    /**
     * 拼接url参数
     */
    @Test
    public void spliceUrlParams() {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("username", "A"));
        params.add(new BasicNameValuePair("password", "123"));
        String uri = URLEncodedUtils.format(params, "utf-8");
        Assert.assertEquals("username=A&password=123", uri);
    }

    @Test
    public void test() throws URISyntaxException {
        URIBuilder builder = new URIBuilder()
                .setScheme("http")
                .setHost("localhost");
        builder.clearParameters()
                .addParameter("A", "1")
                .addParameter("B", "2");
        String reqUrl = builder.setPath("/hello").addParameter("C", "3")
                .build().toString();
        Assert.assertEquals("http://localhost/hello?A=1&B=2&C=3", reqUrl);
    }
}
